package ext.vpde.cadvaulting.service;

import java.io.*;
//import wt.vc.*;
//import wt.fc.*;
import wt.epm.EPMDocument;
import wt.services.StandardManager;
import wt.util.WTException;
//import wt.util.*;
import wt.vc.wip.WorkInProgressServiceEvent;
import wt.events.KeyedEvent;
import wt.events.KeyedEventListener;
//import wt.fc.PersistenceManagerEvent;
import wt.services.ServiceEventListenerAdapter;
import wt.services.ManagerException;
import wt.lifecycle.*;
//import wt.type.TypedUtility;
import ext.vpde.cadvaulting.globalvault.GlobalVault;
//import ext.vpde.cadvaulting.util.ProcessDrawing;
//import ext.vpde.cadvaulting.workflow.*;
/*
 * All of these methods are extensions of OOTB methods. 
 * The only customized part is in notifyVetoableEvent that calls ProcessDrawing and
 * which events to listen for.
 */
public class StandardDrawingService extends StandardManager implements DrawingService, Serializable {

	private static final String CLASSNAME = StandardDrawingService.class.getName();
	private static final long serialVersionUID = 0l;
	private KeyedEventListener listener;

	public String getConceptualClassname() {
		return CLASSNAME;
	}

	public static StandardDrawingService newStandardDrawingService() throws WTException {
		StandardDrawingService instance = new StandardDrawingService();
		instance.initialize();
		return instance;
	}

	class DrawingListener extends ServiceEventListenerAdapter {

		public DrawingListener (String manager_name) {
			super (manager_name);
		}

		public void notifyVetoableEvent (Object event) throws WTException {
			try {
				if (event instanceof KeyedEvent) {
					KeyedEvent keyedEvent = (KeyedEvent) event;
					Object target = keyedEvent.getEventTarget();
					
					if (target instanceof EPMDocument) {
						
						EPMDocument doc = (EPMDocument)target;
						if (doc.getDocType().getStringValue().endsWith("CADDRAWING")) {
							if (keyedEvent.getEventType().equals("STATE_CHANGE")) {
								if (doc.getState().toString().equals("RELEASED")) {
									System.out.println("\nFOUND RELEASE EVENT");
									GlobalVault.getPDF(doc);
								}
							}	
						}
					}
				}
			} catch (Exception e) { e.printStackTrace(); }
		}
	}

	protected void performStartupProcess() throws ManagerException {
		listener = new DrawingListener( this.getConceptualClassname());
		/*
		 * We are only going to listen for the events below. All others are ignored.
		 */
		System.out.println("Drawing Listener Started");
		getManagerService().addEventListener( listener, LifeCycleServiceEvent.generateEventKey("STATE_CHANGE"));
	}
}

